// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/caching/cache_ttl_controller.h>

#include <gtest/gtest.h>
#include <pollux/testing/gtest_utils.h>
#include <pollux/common/caching/async_data_cache.h>
#include <pollux/common/caching/ssd_cache.h>
#include <pollux/common/memory/mmap_allocator.h>

using namespace kumo::pollux;
using namespace kumo::pollux::memory;

namespace kumo::pollux::cache {

class CacheTTLControllerTest : public ::testing::Test {
 protected:
  void SetUp() override {
    allocator_ = std::make_shared<MmapAllocator>(
        MmapAllocator::Options{.capacity = 1024L * 1024L});
    cache_ = AsyncDataCache::create(allocator_.get());
  }

  std::shared_ptr<MemoryAllocator> allocator_;
  std::shared_ptr<AsyncDataCache> cache_;
};

TEST_F(CacheTTLControllerTest, addOpenFileInfo) {
  CacheTTLController::create(*cache_);

  EXPECT_TRUE(CacheTTLController::getInstance()->addOpenFileInfo(123L));
  EXPECT_FALSE(CacheTTLController::getInstance()->addOpenFileInfo(123L));

  EXPECT_TRUE(CacheTTLController::getInstance()->addOpenFileInfo(456L));
}

TEST_F(CacheTTLControllerTest, getCacheAgeStats) {
  CacheTTLController::create(*cache_);

  int64_t fileOpenTime = getCurrentTimeSec();
  for (auto i = 0; i < 1000; i++) {
    CacheTTLController::getInstance()->addOpenFileInfo(i, fileOpenTime + i);
  }

  int64_t current = getCurrentTimeSec();
  EXPECT_GE(
      CacheTTLController::getInstance()->getCacheAgeStats().maxAgeSecs,
      current - fileOpenTime);
}
} // namespace kumo::pollux::cache
